## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005
from CvPythonExtensions import *
import CvUtil
import ScreenInput
import CvScreenEnums
import math

import IconGrid
import CvConfigParser
import CvForeignAdvisor

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# this class is shared by both the resource and technology foreign advisors
FOREIGN_BONUS_SCREEN = 0
FOREIGN_TECH_SCREEN = 1
FOREIGN_RELATIONS_SCREEN = 2
FOREIGN_ACTIVE_TRADE_SCREEN = 3
NUM_FOREIGN_SCREENS = 4


# Change the value to false if the leader names should not be displayed.
# Default value is true
g_bShowLeaderNames = true

# Change the value to false if borders should not be displayed around the rows.
# Default value is true
g_bShowRowBorders = true

# Change the value to increase or decrease the space at the top and bottom ends 
# of the screen.
# Default value is 60
g_iMinimumTopBottomSpace = 60

# Change the value to increase or decrease the space at the right and left ends 
# of the screen.
# Default value is 25
g_iMinimumLeftRightSpace = 25

# Change the value to increase or decrease the extra border at the left and right 
# ends of the column groups in the import and export screens.
# Default value is 8
g_iGroupBorder = 8

# Change the value to increase or decrease the extra space before the label of 
# the column groups in the import and export screens.
# Default value is "   "
g_strGroupLabelOffset = "   "

# Change the value to increase or decrease the minimum space between the columns.
# Default value is 5
g_iMinimumColumnSpace = 5

# Change the value to increase or decrease the minimum space between the rows.
# Default value is 1
g_iMinimumRowSpace = 1

# Change the value to false if the true amount of resources should be shown. If 
# the value is set to true then the amount for each surplus resource is 
# subtracted by one so it shows how many can be traded away without losing access
# to the resource.
# Default value is true
g_bShowExtraResourceAmount = true

# Change the value to false to show the surplus resource amounts below the 
# resources. If the value is set to false it is recommended that 
# g_iSurplusResourceHeight be changed to 110. If the value is set to true then 
# the surplus amounts are shown as an overlay on top of the lowe left corner of 
# the resources.
# Default value is true
g_bShowSurplusResourceAmountOnTop = True

# Change the value to increase or decrease the height of the panel showing the
# surplus resources.
# Default value is 80
g_iSurplusResourceHeight = 80
		
# Change the value to false to ungroup the resource columns. If set to true the
# resource columns will be grouped into import and export columns.
# Default value is true
g_bGroupImportExportResources = true
		
# Change the value to false to hide the columns displaying the resources that are
# in active deals.
# Default value is true
g_bShowActiveResourceDeals = true
		
# Change the value to increase or decrease the width of the column displaying the
# gold amount in active resource deals.
# Default value is 25
g_iResourceGoldColumnWidth = 25		

# Change the value to increase or decrease the spacing between the two panels.
# TODO: find out which two panels this is refering to.
# Default value is 0
g_iResourcePanelSpacing = 0
		
# Change the value to false if large icons (64x64) should be used for 
# technologies instead of small icons (32x32).
# Default value is true
g_bUseSmallTechnologyIcons = true
		
# Change the value to increase or decrease the width of the column displaying the
# gold amount in active technology deals.
# Default value is 25
g_iTechnologyGoldColumnWidth = 60		

g_iTitleHeight = 24

g_iTableControlHeight = 24

g_iResourceIconSize = 34

g_iScrollTableUp = 1

g_iScrollTableDown = 2


class CvEnhancedForeignAdvisor(CvForeignAdvisor.CvForeignAdvisor) :
	"Foreign Advisor Screen"
	
	def __init__(self):
		# initialize base class
		self.parent = CvForeignAdvisor.CvForeignAdvisor
		self.parent.__init__(self)
		
		
	def readConfigurationFile(self):
		global g_bShowLeaderNames 
		global g_bShowRowBorders
		global g_iMinimumTopBottomSpace
		global g_iMinimumLeftRightSpace
		global g_iGroupBorder
		global g_strGroupLabelOffset
		global g_iMinimumColumnSpace
		global g_iMinimumRowSpace

		global g_bShowExtraResourceAmount 
		global g_bShowSurplusResourceAmountOnTop
		global g_iSurplusResourceHeight
		global g_bGroupImportExportResources 
		global g_bShowActiveResourceDeals
		global g_iResourceGoldColumnWidth
		global g_iResourcePanelSpacing 
		global g_bUseSmallTechnologyIcons 
		global g_iTechnologyGoldColumnWidth 

		config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

		if(config != None):
			g_bShowLeaderNames = config.getboolean("Enhanced Foreign Advisor", "Show Leader Names", True)
			g_bShowRowBorders = config.getboolean("Enhanced Foreign Advisor", "Show Row Borders", True)
			g_iMinimumTopBottomSpace = config.getint("Enhanced Foreign Advisor", "Minimum Top Bottom Space", 60)
			g_iMinimumLeftRightSpace = config.getint("Enhanced Foreign Advisor", "Minimum Left Right Space", 25)
			g_iGroupBorder = config.getint("Enhanced Foreign Advisor", "Group Border", 8)
			g_strGroupLabelOffset = config.get("Enhanced Foreign Advisor", "Group Label Offset", "   ").replace("\"","")
			g_iMinimumColumnSpace = config.getint("Enhanced Foreign Advisor", "Minimum Column Space", 5)
			g_iMinimumRowSpace = config.getint("Enhanced Foreign Advisor", "Minimum Column Space", 1)

			g_bShowExtraResourceAmount = config.getboolean("Enhanced Foreign Advisor", "Show Extra Resource Amount", True)
			g_bShowSurplusResourceAmountOnTop = config.getboolean("Enhanced Foreign Advisor", "Show Surplus Resource Amount On Top", True)
			g_iSurplusResourceHeight = config.getint("Enhanced Foreign Advisor", "Surplus Resource Height", 80)
			g_bGroupImportExportResources = config.getboolean("Enhanced Foreign Advisor", "Group Import Export Resources", True)
			g_bShowActiveResourceDeals = config.getboolean("Enhanced Foreign Advisor", "Show Active Resource Deals", True)
			g_iResourceGoldColumnWidth = config.getint("Enhanced Foreign Advisor", "Resource Gold Column Width", 25)
			g_iResourcePanelSpacing = config.getint("Enhanced Foreign Advisor", "Resource Panel Spacing", 0)
			g_bUseSmallTechnologyIcons = config.getboolean("Enhanced Foreign Advisor", "Use Small Technology Icons", True)
			g_iTechnologyGoldColumnWidth = config.getint("Enhanced Foreign Advisor", "Technology Gold Column Width", 60)

	
	def interfaceScreen (self, iScreen):

		self.readConfigurationFile()
		
		self.parent.interfaceScreen(self, iScreen)

				
	# Drawing Leaderheads
	def drawContents(self, bInitial):
	
		if (self.iScreen < 0):
			return
						
		self.deleteAllWidgets()
		
		screen = self.getScreen()

		# Header...
		screen.setLabel(self.getNextWidgetName(), "", self.SCREEN_TITLE, CvUtil.FONT_CENTER_JUSTIFY, self.X_SCREEN, self.Y_TITLE, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1 )
	
		if (self.iScreen == FOREIGN_RELATIONS_SCREEN):
			self.drawRelations(bInitial)
		elif (self.iScreen == FOREIGN_ACTIVE_TRADE_SCREEN):
			self.drawActive()
		elif (self.iScreen == FOREIGN_BONUS_SCREEN):
			self.drawResourceDeals()
		elif (self.iScreen == FOREIGN_TECH_SCREEN):
			self.drawTechDeals()
		else:
			self.drawPossibleDeals()
			
		# Link to other Foreign advisor screens
		xLink = self.X_LINK
		
		szRelationsId = self.getNextWidgetName()
		if (self.iScreen != FOREIGN_RELATIONS_SCREEN):
			screen.setText(szRelationsId, "", u"<font=4>" + localText.getText("TXT_KEY_FOREIGN_ADVISOR_RELATIONS", ()).upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY, xLink, self.Y_LINK, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_FOREIGN_ADVISOR, FOREIGN_RELATIONS_SCREEN, -1)
		else:
			screen.setText(szRelationsId, "", u"<font=4>" + localText.getColorText("TXT_KEY_FOREIGN_ADVISOR_RELATIONS", (), gc.getInfoTypeForString("COLOR_YELLOW")).upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY, xLink, self.Y_LINK, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_FOREIGN_ADVISOR, -1, -1)
		xLink += self.DX_LINK
		
		szBonusId = self.getNextWidgetName()
		if (self.iScreen != FOREIGN_BONUS_SCREEN):
			screen.setText(szBonusId, "", u"<font=4>" + localText.getText("TXT_KEY_FOREIGN_ADVISOR_RESOURCES", ()).upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY, xLink, self.Y_LINK, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_FOREIGN_ADVISOR, FOREIGN_BONUS_SCREEN, -1)
		else:
			screen.setText(szBonusId, "", u"<font=4>" + localText.getColorText("TXT_KEY_FOREIGN_ADVISOR_RESOURCES", (), gc.getInfoTypeForString("COLOR_YELLOW")).upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY, xLink, self.Y_LINK, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_FOREIGN_ADVISOR, -1, -1)
		xLink += self.DX_LINK
			
		szTechId = self.getNextWidgetName()
		if (self.iScreen != FOREIGN_TECH_SCREEN):
			screen.setText(szTechId, "", u"<font=4>" + localText.getText("TXT_KEY_FOREIGN_ADVISOR_TECHS", ()).upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY, xLink, self.Y_LINK, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_FOREIGN_ADVISOR, FOREIGN_TECH_SCREEN, -1)
		else:
			screen.setText(szTechId, "", u"<font=4>" + localText.getColorText("TXT_KEY_FOREIGN_ADVISOR_TECHS", (), gc.getInfoTypeForString("COLOR_YELLOW")).upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY, xLink, self.Y_LINK, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_FOREIGN_ADVISOR, -1, -1)
		xLink += self.DX_LINK
	
		szActiveId = self.getNextWidgetName()
		if (self.iScreen != FOREIGN_ACTIVE_TRADE_SCREEN):
			screen.setText(szActiveId, "", u"<font=4>" + localText.getText("TXT_KEY_FOREIGN_ADVISOR_ACTIVE", ()).upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY, xLink, self.Y_LINK, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_FOREIGN_ADVISOR, FOREIGN_ACTIVE_TRADE_SCREEN, -1)
		else:
			screen.setText(szActiveId, "", u"<font=4>" + localText.getColorText("TXT_KEY_FOREIGN_ADVISOR_ACTIVE", (), gc.getInfoTypeForString("COLOR_YELLOW")).upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY, xLink, self.Y_LINK, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_FOREIGN_ADVISOR, -1, -1)
		xLink += self.DX_LINK


	def initTradeTable(self):
		screen = self.getScreen()
		
		if (g_bShowActiveResourceDeals):
			columns = ( IconGrid.GRID_ICON_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN
					  , IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_TEXT_COLUMN
					  , IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_TEXT_COLUMN )
		else:
			columns = ( IconGrid.GRID_ICON_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN
					  , IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_TEXT_COLUMN )
		self.NUM_RESOURCE_COLUMNS = len(columns) - 1
		
		gridX = g_iMinimumLeftRightSpace + 10
		gridY = g_iMinimumTopBottomSpace + g_iSurplusResourceHeight + g_iResourcePanelSpacing + g_iTitleHeight + 10
		gridWidth = self.W_SCREEN - g_iMinimumLeftRightSpace * 2 - 20
		gridHeight = self.H_SCREEN - g_iMinimumTopBottomSpace * 2 - g_iSurplusResourceHeight - g_iResourcePanelSpacing - g_iTitleHeight - 20
		
		self.resIconGridName = self.getNextWidgetName()
		self.resIconGrid = IconGrid.IconGrid( self.resIconGridName, screen, gridX, gridY, gridWidth, gridHeight
											, columns, True, g_bShowLeaderNames , g_bShowRowBorders )

		self.resIconGrid.setGroupBorder(g_iGroupBorder)
		self.resIconGrid.setGroupLabelOffset(g_strGroupLabelOffset)
		self.resIconGrid.setMinColumnSpace(g_iMinimumColumnSpace)
		self.resIconGrid.setMinRowSpace(g_iMinimumRowSpace)
		
		self.leaderCol = 0
		self.surplusCol = 1
		self.usedCol = 2
		self.willTradeCol = 3
		self.wontTradeCol = 4
		self.canPayCol = 5
		self.activeExportCol = 6
		self.activeImportCol = 7
		self.payingCol = 8
		
		self.resIconGrid.setHeader( self.leaderCol, localText.getText("TXT_KEY_FOREIGN_ADVISOR_LEADER", ()) )
		self.resIconGrid.setHeader( self.surplusCol, localText.getText("TXT_KEY_FOREIGN_ADVISOR_SURPLUS", ()) )
		self.resIconGrid.setHeader( self.usedCol, localText.getText("TXT_KEY_FOREIGN_ADVISOR_USED", ()) )
		self.resIconGrid.setHeader( self.willTradeCol, localText.getText("TXT_KEY_FOREIGN_ADVISOR_FOR_TRADE_2", ()) )
		self.resIconGrid.setHeader( self.wontTradeCol, localText.getText("TXT_KEY_FOREIGN_ADVISOR_NOT_FOR_TRADE_2", ()) )
		self.resIconGrid.setHeader( self.canPayCol, (u"%c" % gc.getCommerceInfo(CommerceTypes.COMMERCE_GOLD).getChar()) )
		self.resIconGrid.setTextColWidth(self.canPayCol, g_iResourceGoldColumnWidth)
		
		if (g_bShowActiveResourceDeals):
			self.resIconGrid.setHeader( self.activeExportCol, localText.getText("TXT_KEY_FOREIGN_ADVISOR_EXPORT", ()) )
			self.resIconGrid.setHeader( self.activeImportCol, localText.getText("TXT_KEY_FOREIGN_ADVISOR_IMPORT", ()) )
			self.resIconGrid.setHeader( self.payingCol, (u"%c" % gc.getCommerceInfo(CommerceTypes.COMMERCE_GOLD).getChar()) )
			self.resIconGrid.setTextColWidth(self.payingCol, g_iResourceGoldColumnWidth)
		if (g_bGroupImportExportResources):
			self.resIconGrid.createColumnGroup("", 1)
			self.resIconGrid.createColumnGroup(localText.getText("TXT_KEY_FOREIGN_ADVISOR_EXPORT", ()), 2)
			self.resIconGrid.createColumnGroup(localText.getText("TXT_KEY_FOREIGN_ADVISOR_IMPORT", ()), 3)
			if (g_bShowActiveResourceDeals):
				self.resIconGrid.createColumnGroup(localText.getText("TXT_KEY_FOREIGN_ADVISOR_ACTIVE", ()), 3)
		
		gridWidth = self.resIconGrid.getPrefferedWidth()
		gridHeight = self.resIconGrid.getPrefferedHeight()
		self.RES_LEFT_RIGHT_SPACE = (self.W_SCREEN - gridWidth - 20) / 2
		self.RES_TOP_BOTTOM_SPACE = (self.H_SCREEN - gridHeight - g_iSurplusResourceHeight - g_iResourcePanelSpacing - g_iTitleHeight - 20) / 2
		gridX = self.RES_LEFT_RIGHT_SPACE + 10
		gridY = self.RES_TOP_BOTTOM_SPACE + g_iSurplusResourceHeight + g_iResourcePanelSpacing + g_iTitleHeight + 10
		
		self.resIconGrid.setPosition(gridX, gridY)
		self.resIconGrid.setSize(gridWidth, gridHeight)

		
	def calculateSuplusPanelLayout(self):
		self.SURPLUS_X = self.RES_LEFT_RIGHT_SPACE
		self.SURPLUS_Y = self.RES_TOP_BOTTOM_SPACE
		self.SURPLUS_WIDTH = self.W_SCREEN - 2 * self.RES_LEFT_RIGHT_SPACE
		
		self.SURPLUS_ICONS_X = self.SURPLUS_X + 10
		if (g_bShowSurplusResourceAmountOnTop):
			self.SURPLUS_TABLE_X = self.SURPLUS_ICONS_X + 15
			SURPLUS_VERTICAL_SPACING = (g_iSurplusResourceHeight - g_iResourceIconSize - g_iTitleHeight) / 2
			self.SURPLUS_ICONS_Y = self.SURPLUS_Y + SURPLUS_VERTICAL_SPACING + g_iTitleHeight
			self.SURPLUS_TABLE_Y = self.SURPLUS_ICONS_Y + (g_iResourceIconSize - g_iTableControlHeight) / 2 + 8
		else:
			self.SURPLUS_TABLE_X = self.SURPLUS_ICONS_X + 5
			SURPLUS_VERTICAL_SPACING = ( g_iSurplusResourceHeight - g_iResourceIconSize - g_iTableControlHeight 
									   - g_iTitleHeight ) / 2 + 3
			self.SURPLUS_ICONS_Y = self.SURPLUS_Y + SURPLUS_VERTICAL_SPACING + g_iTitleHeight
			self.SURPLUS_TABLE_Y = self.SURPLUS_ICONS_Y + g_iResourceIconSize
		
		self.SURPLUS_CIRCLE_X_START = self.SURPLUS_TABLE_X + 4
		self.SURPLUS_CIRCLE_Y = self.SURPLUS_TABLE_Y + 5

		
	def drawResourceDeals(self):
		screen = self.getScreen()
		activePlayer = gc.getPlayer(self.iActiveLeader)
		self.initTradeTable()
		
		# Find all the surplus resources
		tradeData = TradeData()
		tradeData.ItemType = TradeableItems.TRADE_RESOURCES
		listSurplus = []
		
		for iLoopBonus in range(gc.getNumBonusInfos()):
			tradeData.iData = iLoopBonus
			for iLoopPlayer in range(gc.getMAX_PLAYERS()):
				currentPlayer = gc.getPlayer(iLoopPlayer)
				if ( gc.getPlayer(iLoopPlayer).isAlive() and not gc.getPlayer(iLoopPlayer).isBarbarian()
														  and not gc.getPlayer(iLoopPlayer).isMinorCiv() 
														  and gc.getTeam(currentPlayer.getTeam()).isHasMet(activePlayer.getTeam())
														  and iLoopPlayer != self.iActiveLeader 
														  and activePlayer.canTradeItem(iLoopPlayer, tradeData, False)
														  and activePlayer.getNumTradeableBonuses(iLoopBonus) > 1 ):
					listSurplus.append(iLoopBonus)
					break
		
		self.calculateSuplusPanelLayout()
		
		# Assemble the surplus panel
		self.mainAvailablePanel = self.getNextWidgetName()
		screen.addPanel( self.mainAvailablePanel, localText.getText("TXT_KEY_FOREIGN_ADVISOR_SURPLUS_RESOURCES", ()), ""
					   , False, False, self.SURPLUS_X, self.SURPLUS_Y, self.SURPLUS_WIDTH, g_iSurplusResourceHeight
					   , PanelStyles.PANEL_STYLE_MAIN )
		
		self.availableMultiList = self.getNextWidgetName()
		screen.addMultiListControlGFC( self.availableMultiList, ""
									 , self.SURPLUS_ICONS_X, self.SURPLUS_ICONS_Y
									 , g_iResourceIconSize * len(listSurplus), g_iResourceIconSize
									 , 1, 32, 32, TableStyles.TABLE_STYLE_EMPTY )

		self.availableTable = self.getNextWidgetName()
		# add the circles behind the amounts
		if (g_bShowSurplusResourceAmountOnTop):
			for iIndex in range(len(listSurplus)):
				screen.addDDSGFC( self.availableTable + "Circle" + str(iIndex)
								 , ArtFileMgr.getInterfaceArtInfo("WHITE_CIRCLE_40").getPath()
								 , self.SURPLUS_CIRCLE_X_START + iIndex * g_iResourceIconSize, self.SURPLUS_CIRCLE_Y
								 , 16, 16, WidgetTypes.WIDGET_GENERAL, -1, -1 )
		
		# add the table showing the amounts
		screen.addTableControlGFC( self.availableTable, len(listSurplus)
							     , self.SURPLUS_TABLE_X, self.SURPLUS_TABLE_Y
							     , len(listSurplus) * g_iResourceIconSize, g_iTableControlHeight
							     , False, False, 16, 16, TableStyles.TABLE_STYLE_EMPTY )
		
		# Add the bonuses to the surplus panel with their amount
		for iIndex in range(len(listSurplus)):
			screen.appendMultiListButton( self.availableMultiList, gc.getBonusInfo(listSurplus[iIndex]).getButton(), 0
										, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, listSurplus[iIndex], -1, False )
			screen.setTableColumnHeader( self.availableTable, iIndex, u"", g_iResourceIconSize )
			
			amount = activePlayer.getNumTradeableBonuses(listSurplus[iIndex])
			if (g_bShowExtraResourceAmount):
				amount = amount - 1
			
			if (g_bShowSurplusResourceAmountOnTop):
				amountStr = u"<font=2>" + localText.changeTextColor(str(amount), gc.getInfoTypeForString("COLOR_YELLOW")) + "</font>"
			else:
				amountStr = u"<font=3>" + str(amount) + "</font>"
			screen.setTableText( self.availableTable, iIndex, 0, amountStr, "", WidgetTypes.WIDGET_GENERAL, -1, -1, 0 )
				
 		# Assemble the panel that shows the trade table
		self.TABLE_PANEL_X = self.RES_LEFT_RIGHT_SPACE
		self.TABLE_PANEL_Y = self.SURPLUS_Y + g_iSurplusResourceHeight + g_iResourcePanelSpacing
		self.TABLE_PANEL_WIDTH = self.W_SCREEN - 2 * self.RES_LEFT_RIGHT_SPACE
		self.TABLE_PANEL_HEIGHT = self.H_SCREEN - self.TABLE_PANEL_Y - self.RES_TOP_BOTTOM_SPACE
		
		self.tradePanel = self.getNextWidgetName()
		screen.addPanel( self.tradePanel, localText.getText("TXT_KEY_FOREIGN_ADVISOR_TRADE_TABLE", ()), ""
					   , True, True, self.TABLE_PANEL_X, self.TABLE_PANEL_Y, self.TABLE_PANEL_WIDTH, self.TABLE_PANEL_HEIGHT
					   , PanelStyles.PANEL_STYLE_MAIN )
		
		self.resIconGrid.createGrid()
		
		# find all players that need to be listed 
		self.resIconGrid.clearData()
		tradeData = TradeData()
		tradeData.ItemType = TradeableItems.TRADE_RESOURCES
		currentRow = 0
		
		for iLoopPlayer in range(gc.getMAX_PLAYERS()):
			currentPlayer = gc.getPlayer(iLoopPlayer)
			if ( currentPlayer.isAlive() and not currentPlayer.isBarbarian() and not currentPlayer.isMinorCiv() 
										 and gc.getTeam(currentPlayer.getTeam()).isHasMet(activePlayer.getTeam()) 
										 and iLoopPlayer != self.iActiveLeader ):
				message = ""
				if ( not activePlayer.canTradeNetworkWith(iLoopPlayer) ):
					message = localText.getText("TXT_KEY_FOREIGN_ADVISOR_NOT_CONNECTED", ())
				
				self.resIconGrid.appendRow(currentPlayer.getName(), message)
				self.resIconGrid.addIcon( currentRow, self.leaderCol
										, gc.getLeaderHeadInfo(currentPlayer.getLeaderType()).getButton()
										, WidgetTypes.WIDGET_LEADERHEAD, iLoopPlayer )

				for iLoopBonus in range(gc.getNumBonusInfos()):
					if (gc.getTeam(activePlayer.getTeam()).isGoldTrading() or gc.getTeam(currentPlayer.getTeam()).isGoldTrading()):
						sAmount = str(gc.getPlayer(iLoopPlayer).AI_maxGoldPerTurnTrade(self.iActiveLeader))
						self.resIconGrid.setText(currentRow, self.canPayCol, sAmount)
					
					tradeData.iData = iLoopBonus
					if ( activePlayer.canTradeItem(iLoopPlayer, tradeData, False) ):
						if ( activePlayer.getNumTradeableBonuses(iLoopBonus) > 1 ): # surplus
							self.resIconGrid.addIcon( currentRow, self.surplusCol, gc.getBonusInfo(iLoopBonus).getButton()
													, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, iLoopBonus )
						else: # used
							self.resIconGrid.addIcon( currentRow, self.usedCol, gc.getBonusInfo(iLoopBonus).getButton()
													, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, iLoopBonus )
					elif (currentPlayer.canTradeItem(self.iActiveLeader, tradeData, False)):
						if (currentPlayer.getTradeDenial(self.iActiveLeader, tradeData) == DenialTypes.NO_DENIAL): # will trade
							self.resIconGrid.addIcon( currentRow, self.willTradeCol, gc.getBonusInfo(iLoopBonus).getButton()
													, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, iLoopBonus )
						else: # won't trade
							self.resIconGrid.addIcon( currentRow, self.wontTradeCol, gc.getBonusInfo(iLoopBonus).getButton()
													, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, iLoopBonus )
				if (g_bShowActiveResourceDeals):
					amount = 0
					for iLoopDeal in range(gc.getGame().getIndexAfterLastDeal()):
						deal = gc.getGame().getDeal(iLoopDeal)
						if ( deal.getFirstPlayer() == iLoopPlayer and deal.getSecondPlayer() == self.iActiveLeader 
																  and not deal.isNone() ):
							for iLoopTradeItem in range(deal.getLengthFirstTrades()):
								tradeData2 = deal.getFirstTrade(iLoopTradeItem)
								if (tradeData2.ItemType == TradeableItems.TRADE_GOLD_PER_TURN):
									amount += tradeData2.iData
								if (tradeData2.ItemType == TradeableItems.TRADE_RESOURCES):
									self.resIconGrid.addIcon( currentRow, self.activeImportCol
															, gc.getBonusInfo(tradeData2.iData).getButton()
															, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, tradeData2.iData )
							for iLoopTradeItem in range(deal.getLengthSecondTrades()):
								tradeData2 = deal.getSecondTrade(iLoopTradeItem)
								if (tradeData2.ItemType == TradeableItems.TRADE_GOLD_PER_TURN):
									amount -= tradeData2.iData
								if (tradeData2.ItemType == TradeableItems.TRADE_RESOURCES):
									self.resIconGrid.addIcon( currentRow, self.activeExportCol
															, gc.getBonusInfo(tradeData2.iData).getButton()
															, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, tradeData2.iData )
						
						if ( deal.getSecondPlayer() == iLoopPlayer and deal.getFirstPlayer() == self.iActiveLeader ):
							for iLoopTradeItem in range(deal.getLengthFirstTrades()):
								tradeData2 = deal.getFirstTrade(iLoopTradeItem)
								if (tradeData2.ItemType == TradeableItems.TRADE_GOLD_PER_TURN):
									amount -= tradeData2.iData
								if (tradeData2.ItemType == TradeableItems.TRADE_RESOURCES):
									self.resIconGrid.addIcon( currentRow, self.activeExportCol
															, gc.getBonusInfo(tradeData2.iData).getButton()
															, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, tradeData2.iData )
							for iLoopTradeItem in range(deal.getLengthSecondTrades()):
								tradeData2 = deal.getSecondTrade(iLoopTradeItem)
								if (tradeData2.ItemType == TradeableItems.TRADE_GOLD_PER_TURN):
									amount += tradeData2.iData
								if (tradeData2.ItemType == TradeableItems.TRADE_RESOURCES):
									self.resIconGrid.addIcon( currentRow, self.activeImportCol
															, gc.getBonusInfo(tradeData2.iData).getButton()
															, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, tradeData2.iData )
					if (amount != 0):
						self.resIconGrid.setText(currentRow, self.payingCol, str(amount))
				currentRow += 1
		self.resIconGrid.refresh()
	
	
	def scrollTradeTableUp(self):
		if (self.iScreen == FOREIGN_BONUS_SCREEN):
			self.resIconGrid.scrollUp()
		elif (self.iScreen == FOREIGN_TECH_SCREEN):
			self.techIconGrid.scrollUp()


	def scrollTradeTableDown(self):
		if (self.iScreen == FOREIGN_BONUS_SCREEN):
			self.resIconGrid.scrollDown()
		elif (self.iScreen == FOREIGN_TECH_SCREEN):
			self.techIconGrid.scrollDown()
				
		
	def drawTechDeals(self):
		screen = self.getScreen()
		activePlayer = gc.getPlayer(self.iActiveLeader)
		self.initTechTable()
		
		# Assemble the panel
		TECH_PANEL_X = self.TECH_LEFT_RIGHT_SPACE
		TECH_PANEL_Y = self.TECH_TOP_BOTTOM_SPACE
		TECH_PANEL_WIDTH = self.W_SCREEN - 2 * self.TECH_LEFT_RIGHT_SPACE
		TECH_PANEL_HEIGHT = self.H_SCREEN - 2 * self.TECH_TOP_BOTTOM_SPACE
		
		self.tradePanel = self.getNextWidgetName()
		screen.addPanel( self.tradePanel, "", "", True, True
					   , TECH_PANEL_X, TECH_PANEL_Y, TECH_PANEL_WIDTH, TECH_PANEL_HEIGHT
					   , PanelStyles.PANEL_STYLE_MAIN )
		
		self.techIconGrid.createGrid()
		
		self.techIconGrid.clearData()
		tradeData = TradeData()
		tradeData.ItemType = TradeableItems.TRADE_TECHNOLOGIES
		currentRow = 0
		
		for iLoopPlayer in range(gc.getMAX_PLAYERS()):
			currentPlayer = gc.getPlayer(iLoopPlayer)
			if ( currentPlayer.isAlive() and not currentPlayer.isBarbarian() and not currentPlayer.isMinorCiv() 
										 and gc.getTeam(currentPlayer.getTeam()).isHasMet(activePlayer.getTeam()) 
										 and iLoopPlayer != self.iActiveLeader ):
				message = ""
				if ( not gc.getTeam(activePlayer.getTeam()).isTechTrading() and not gc.getTeam(currentPlayer.getTeam()).isTechTrading() ):
					message = localText.getText("TXT_KEY_FOREIGN_ADVISOR_NO_TECH_TRADING", ())

				self.techIconGrid.appendRow(currentPlayer.getName(), message)
				self.techIconGrid.addIcon( currentRow, 0, gc.getLeaderHeadInfo(currentPlayer.getLeaderType()).getButton()
										 , WidgetTypes.WIDGET_LEADERHEAD, iLoopPlayer )
				
				if (gc.getTeam(activePlayer.getTeam()).isGoldTrading() or gc.getTeam(currentPlayer.getTeam()).isGoldTrading()):
					sAmount = str(gc.getPlayer(iLoopPlayer).AI_maxGoldTrade(self.iActiveLeader))
					self.techIconGrid.setText(currentRow, 4, sAmount)
				
				for iLoopTech in range(gc.getNumTechInfos()):
					tradeData.iData = iLoopTech
					if (activePlayer.canTradeItem(iLoopPlayer, tradeData, False)): # wants
						self.techIconGrid.addIcon( currentRow, 1, gc.getTechInfo(iLoopTech).getButton()
												 , WidgetTypes.WIDGET_PEDIA_JUMP_TO_TECH, iLoopTech )
					if (currentPlayer.canTradeItem(self.iActiveLeader, tradeData, False)):
						if (currentPlayer.getTradeDenial(self.iActiveLeader, tradeData) == DenialTypes.NO_DENIAL): # will trade
							self.techIconGrid.addIcon( currentRow, 2, gc.getTechInfo(iLoopTech).getButton()
													 , WidgetTypes.WIDGET_PEDIA_JUMP_TO_TECH, iLoopTech )
						else: # won't trade
							self.techIconGrid.addIcon( currentRow, 3, gc.getTechInfo(iLoopTech).getButton()
													 , WidgetTypes.WIDGET_PEDIA_JUMP_TO_TECH, iLoopTech )
				currentRow += 1
		self.techIconGrid.refresh()
													 

	def initTechTable(self):
		screen = self.getScreen()
		
		gridX = g_iMinimumLeftRightSpace + 10
		gridY = g_iMinimumTopBottomSpace + 10
		gridWidth = self.W_SCREEN - g_iMinimumLeftRightSpace * 2 - 20
		gridHeight = self.H_SCREEN - g_iMinimumTopBottomSpace * 2 - 20
		
		columns = ( IconGrid.GRID_ICON_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN
				  , IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_MULTI_LIST_COLUMN, IconGrid.GRID_TEXT_COLUMN )
		self.techIconGridName = self.getNextWidgetName()
		self.techIconGrid = IconGrid.IconGrid( self.techIconGridName, screen, gridX, gridY, gridWidth, gridHeight
											 , columns, g_bUseSmallTechnologyIcons, g_bShowLeaderNames , g_bShowRowBorders )

		self.techIconGrid.setGroupBorder(g_iGroupBorder)
		self.techIconGrid.setGroupLabelOffset(g_strGroupLabelOffset)
		self.techIconGrid.setMinColumnSpace(g_iMinimumColumnSpace)
		self.techIconGrid.setMinRowSpace(g_iMinimumRowSpace)
		
		self.techIconGrid.setHeader( 0, localText.getText("TXT_KEY_FOREIGN_ADVISOR_LEADER", ()) )
		self.techIconGrid.setHeader( 1, localText.getText("TXT_KEY_FOREIGN_ADVISOR_WANTS", ()) )
		self.techIconGrid.setHeader( 2, localText.getText("TXT_KEY_FOREIGN_ADVISOR_FOR_TRADE_2", ()) )
		self.techIconGrid.setHeader( 3, localText.getText("TXT_KEY_FOREIGN_ADVISOR_NOT_FOR_TRADE_2", ()) )
		self.techIconGrid.setHeader( 4, (u"%c" % gc.getCommerceInfo(CommerceTypes.COMMERCE_GOLD).getChar()) )
		self.techIconGrid.setTextColWidth( 4, g_iTechnologyGoldColumnWidth )
		
		gridWidth = self.techIconGrid.getPrefferedWidth()
		gridHeight = self.techIconGrid.getPrefferedHeight()
		self.TECH_LEFT_RIGHT_SPACE = (self.W_SCREEN - gridWidth - 20) / 2
		self.TECH_TOP_BOTTOM_SPACE = (self.H_SCREEN - gridHeight - 20) / 2
		gridX = self.TECH_LEFT_RIGHT_SPACE + 10
		gridY = self.TECH_TOP_BOTTOM_SPACE + 10
		
		self.techIconGrid.setPosition(gridX, gridY)
		self.techIconGrid.setSize(gridWidth, gridHeight)
							

	# Handles the input for this screen...
	def handleInput (self, inputClass):
		if (inputClass.getNotifyCode() == NotifyCode.NOTIFY_CLICKED):
			if (inputClass.getButtonType() == WidgetTypes.WIDGET_LEADERHEAD):
				if (inputClass.getFlags() & MouseFlags.MOUSE_LBUTTONUP):
					self.iSelectedLeader = inputClass.getData1()
					self.drawContents(False)
				elif (inputClass.getFlags() & MouseFlags.MOUSE_RBUTTONUP):
					if (self.iActiveLeader != inputClass.getData1()):
						self.getScreen().hideScreen()

			elif (inputClass.getButtonType() == WidgetTypes.WIDGET_GENERAL):
				if (inputClass.getData1() == g_iScrollTableUp):
					self.scrollTradeTableUp()
				elif (inputClass.getData1() == g_iScrollTableDown):
					self.scrollTradeTableDown()
			 
		elif (inputClass.getNotifyCode() == NotifyCode.NOTIFY_LISTBOX_ITEM_SELECTED):
			if (inputClass.getFunctionName() + str(inputClass.getID()) == self.getWidgetName(self.DEBUG_DROPDOWN_ID)):
				print 'debug dropdown event'
				szName = self.getWidgetName(self.DEBUG_DROPDOWN_ID)
				iIndex = self.getScreen().getSelectedPullDownID(szName)
				self.iActiveLeader = self.getScreen().getPullDownData(szName, iIndex)
				self.drawContents(False)
		elif (inputClass.getNotifyCode() == NotifyCode.NOTIFY_CHARACTER):
			if (inputClass.getData() == int(InputTypes.KB_LSHIFT) or inputClass.getData() == int(InputTypes.KB_RSHIFT)):
				self.iShiftKeyDown = inputClass.getID() 

		return 0
